/*
  EOMono
  Copyright 2007, Adam Tauno Williams (Whitemice Consulting)
  License: LGPLv2  < http://www.gnu.org/licenses/lgpl-2.1.html >
 */
using System;

namespace Whitemice.EOMono
{
  [EOCommandAttribute("SQLDelete", 1, "Delete the provided record")]
  public class EOSQLDeleteCommand : EOSQLCommand, IEOCommand
  {
    protected IEORecord  record = null;
  
    public EOSQLDeleteCommand(IEOConnection _connection, string _entity) :
      base(_connection, _entity)
    {
    }
    
    [EOArguementAttribute("record", "")]
    public IEORecord Record
    {
      set { record = value; }
      get { return record; }
    }
    
    protected override void Execute()
    {
      string      sql;
      bool        first = true;
      
      if (Record == null)
        throw new Exception("Delete command with no record");
        
      if (Record.IsNew)
        throw new Exception("Delete command with uncommitted record");
      if (!(Record.IsUpdateComplete))
        throw new Exception("Delete command with incomplete record");
        
      sql = string.Format("DELETE FROM {0} WHERE ", Entity.InternalName);
      foreach(string field in Entity.PrimaryKeys)
      {
        if (first)
          first = false;
        else sql = string.Format("{0} AND ", sql);
        if (record[field].HasValue)
          sql = string.Format("{0} {1} = {2}", sql, field, record.SQLValue(field));
        else throw new Exception("Primary key cannot be NULL");
      } /* end build-where-clause */
      command.CommandText = sql;
      EOManager.Log.DebugFormat("SQL:{0}", sql);
      command.ExecuteNonQuery();
    } // end Execute
  }
}
